<template>
	<div class="card-fill layout-padding attendance-shift" v-loading="loading" element-loading-text="Loading...">
		<el-tabs v-model="activeTab" type="border-card">
			<el-tab-pane label="基本信息" name="main">
				<el-card shadow="hover" class="layout-padding-auto create-form">
					<el-form ref="formRef" :model="stateData.vmModel" label-width="120px">
						<div class="form-section">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
								<span>基本信息</span>
							</div>

							<el-row :gutter="20">
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item
										ref="Entity_Name_FormItem"
										prop="Entity.Name"
										:rules="[{ required: true, message: '班次名称为必填项', trigger: 'blur' }]"
									>
										<template #label>
											<WtmLabelTooltip label="班次名称" tooltip="考勤班次规则的显示名称" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.Name" clearable class="width100"></el-input>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item
										ref="Entity_DisplayColor_FormItem"
										prop="Entity.DisplayColor"
										:rules="[{ required: true, message: '显示颜色为必填项', trigger: 'blur' }]"
									>
										<template #label>
											<WtmLabelTooltip label="显示颜色" tooltip="为当前班次标记颜色，便于在排班表中能快速区分不同班次" />
										</template>
										<div class="color-picker-container">
											<el-color-picker
												v-model="stateData.vmModel.Entity.DisplayColor"
												class="color-picker-main"
												show-alpha
												:predefine="predefineColors"
											/>
											<div class="color-preview">
												<div class="color-preview-block" :style="{ backgroundColor: stateData.vmModel.Entity.DisplayColor || '#409EFF' }"></div>
												<span class="color-preview-text">{{ stateData.vmModel.Entity.DisplayColor || '#409EFF' }}</span>
											</div>
										</div>
									</el-form-item>
								</el-col>
								<!-- <el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_Tag_FormItem" prop="Entity.Tag">
										<template #label>
											<WtmLabelTooltip label="班次标签" tooltip="班次类型标签（白班/中班/夜班）" />
										</template>
										<el-select v-model="stateData.vmModel.Entity.Tag" clearable class="width100">
											<el-option key="A" value="A" label="A"></el-option>
											<el-option key="B" value="B" label="B"></el-option>
											<el-option key="C" value="C" label="C"></el-option>
										</el-select>
									</el-form-item>
								</el-col> -->
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item
										ref="Entity_IsEnabled_FormItem"
										prop="Entity.IsEnabled"
										:rules="[{ required: true, message: '是否启用为必填项', trigger: 'blur' }]"
									>
										<template #label>
											<WtmLabelTooltip label="是否启用" tooltip="班次规则是否生效" />
										</template>
										<el-select v-model="stateData.vmModel.Entity.IsEnabled" clearable class="width100">
											<el-option :key="1" :value="true" :label="$t('message._system.common.vm.tips_bool_true')"></el-option>
											<el-option :key="0" :value="false" :label="$t('message._system.common.vm.tips_bool_false')"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item
										ref="Entity_IsDefault_FormItem"
										prop="Entity.IsDefault"
										:rules="[{ required: true, message: '是否默认班次为必填项', trigger: 'blur' }]"
									>
										<template #label>
											<WtmLabelTooltip label="是否默认班次" tooltip="是否默认员工班次，默认班次将作为员工班次的首选" />
										</template>
										<el-select v-model="stateData.vmModel.Entity.IsDefault" clearable class="width100">
											<el-option :key="1" :value="true" :label="$t('message._system.common.vm.tips_bool_true')"></el-option>
											<el-option :key="0" :value="false" :label="$t('message._system.common.vm.tips_bool_false')"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item
										ref="Entity_Order_FormItem"
										prop="Entity.Order"
									>
										<template #label>
											<WtmLabelTooltip label="排序" tooltip="班次规则的排序" />
										</template>
										<el-input-number v-model="stateData.vmModel.Entity.Order" class="width100" :min="0"></el-input-number>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="24" class="mb20">
									<el-form-item ref="Entity_Remark_FormItem" prop="Entity.Remark">
										<template #label>
											<WtmLabelTooltip label="备注" tooltip="班次规则的备注信息" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.Remark" type="textarea" :rows="3" clearable></el-input>
									</el-form-item>
								</el-col>
							</el-row>
						</div>

						<div class="form-section">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-clock"></i>
								<span>打卡设置</span>
							</div>

							<div class="punch-settings-table">
								<div class="punch-table-header">
									<div class="header-col col-type">类型</div>
									<div class="header-col col-worktime">上班时间</div>
									<div class="header-col col-punchtime">打卡有效时间</div>
								</div>
								<div class="punch-table-row">
									<div class="row-col col-type">
										<div class="type-label">
											<i class="el-icon-sunrise type-icon work-start"></i>
											<span>上班</span>
										</div>
									</div>
									<div class="row-col col-worktime">
										<div class="worktime-group">
											<div class="time-group">
												<el-select v-model="stateData.vmModel.Entity.WorkStartDayOffset" class="day-select-compact">
													<el-option key="当日" value="当日" label="当日"></el-option>
													<el-option key="下一日" value="下一日" label="下一日"></el-option>
													<el-option key="上一日" value="上一日" label="上一日"></el-option>
												</el-select>
												<el-form-item
													prop="Entity.WorkStartTime"
													:rules="[{ required: true, message: '上班时间为必填项', trigger: 'blur' }]"
													class="inline-form-item"
													label-width="20px"
												>
													<el-time-picker v-model="workStartTime" class="time-picker-compact"></el-time-picker>
												</el-form-item>
											</div>
										</div>
									</div>
									<div class="row-col col-punchtime">
										<div class="punchtime-range">
											<div class="time-group">
												<el-select v-model="stateData.vmModel.Entity.WorkStartPunchStartDayOffset" class="day-select-mini">
													<el-option key="当日" value="当日" label="当日"></el-option>
													<el-option key="下一日" value="下一日" label="下一日"></el-option>
													<el-option key="上一日" value="上一日" label="上一日"></el-option>
												</el-select>
												<el-form-item
													prop="Entity.WorkStartPunchStartTime"
													:rules="[{ required: true, message: '开始时间必填', trigger: 'blur' }]"
													class="inline-form-item"
													label-width="20px"
												>
													<el-time-picker v-model="workStartPunchStartTime" class="time-picker-mini"></el-time-picker>
												</el-form-item>
											</div>
											<span class="range-separator">~</span>
											<div class="time-group">
												<el-select v-model="stateData.vmModel.Entity.WorkStartPunchEndDayOffset" class="day-select-mini">
													<el-option key="当日" value="当日" label="当日"></el-option>
													<el-option key="下一日" value="下一日" label="下一日"></el-option>
													<el-option key="上一日" value="上一日" label="上一日"></el-option>
												</el-select>
												<el-form-item
													prop="Entity.WorkStartPunchEndTime"
													:rules="[{ required: true, message: '结束时间必填', trigger: 'blur' }]"
													class="inline-form-item"
													label-width="20px"
												>
													<el-time-picker v-model="workStartPunchEndTime" class="time-picker-mini"></el-time-picker>
												</el-form-item>
											</div>
										</div>
									</div>
								</div>
								<div class="punch-table-row">
									<div class="row-col col-type">
										<div class="type-label">
											<i class="el-icon-sunset type-icon work-end"></i>
											<span>下班</span>
										</div>
									</div>
									<div class="row-col col-worktime">
										<div class="worktime-group">
											<div class="time-group">
												<el-select v-model="stateData.vmModel.Entity.WorkEndDayOffset" class="day-select-compact">
													<el-option key="当日" value="当日" label="当日"></el-option>
													<el-option key="下一日" value="下一日" label="下一日"></el-option>
													<el-option key="上一日" value="上一日" label="上一日"></el-option>
												</el-select>
												<el-form-item
													prop="Entity.WorkEndTime"
													:rules="[{ required: true, message: '下班时间为必填项', trigger: 'blur' }]"
													class="inline-form-item"
													label-width="20px"
												>
													<el-time-picker v-model="workEndTime" class="time-picker-compact"></el-time-picker>
												</el-form-item>
											</div>
										</div>
									</div>
									<div class="row-col col-punchtime">
										<div class="punchtime-range">
											<div class="time-group">
												<el-select v-model="stateData.vmModel.Entity.WorkEndPunchStartDayOffset" class="day-select-mini">
													<el-option key="当日" value="当日" label="当日"></el-option>
													<el-option key="下一日" value="下一日" label="下一日"></el-option>
													<el-option key="上一日" value="上一日" label="上一日"></el-option>
												</el-select>
												<el-form-item
													prop="Entity.WorkEndPunchStartTime"
													:rules="[{ required: true, message: '开始时间必填', trigger: 'blur' }]"
													class="inline-form-item"
													label-width="20px"
												>
													<el-time-picker v-model="workEndPunchStartTime" class="time-picker-mini"></el-time-picker>
												</el-form-item>
											</div>
											<span class="range-separator">~</span>
											<div class="time-group">
												<el-select v-model="stateData.vmModel.Entity.WorkEndPunchEndDayOffset" class="day-select-mini">
													<el-option key="当日" value="当日" label="当日"></el-option>
													<el-option key="下一日" value="下一日" label="下一日"></el-option>
													<el-option key="上一日" value="上一日" label="上一日"></el-option>
												</el-select>
												<el-form-item
													prop="Entity.WorkEndPunchEndTime"
													:rules="[{ required: true, message: '结束时间必填', trigger: 'blur' }]"
													class="inline-form-item"
													label-width="20px"
												>
													<el-time-picker v-model="workEndPunchEndTime" class="time-picker-mini"></el-time-picker>
												</el-form-item>
											</div>
										</div>
									</div>
								</div>
							</div>
						</div>

						<div class="form-section">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-warning"></i>
								<span>违规规则</span>
								<div class="section-switch">
									<span class="switch-label">启用违规规则</span>
									<el-switch v-model="stateData.vmModel.Entity.AttendanceViolationRuleEnabled"></el-switch>
								</div>
							</div>

							<div class="violation-rules-grid">
								<div class="rule-item" :class="{ 'rule-disabled': !stateData.vmModel.Entity.AttendanceViolationRuleEnabled }">
									<div class="rule-label">
										<span class="rule-text">迟到阈值</span>
									</div>
									<div class="rule-input-group">
										<el-input-number
											v-model="stateData.vmModel.Entity.LateMinutesThreshold"
											:disabled="!stateData.vmModel.Entity.AttendanceViolationRuleEnabled"
											class="rule-input"
											:min="0"
										></el-input-number>
										<span class="rule-unit">分钟</span>
										<span class="rule-desc">超过标准上班时间多少分钟算作迟到</span>
									</div>
								</div>
								<div class="rule-item" :class="{ 'rule-disabled': !stateData.vmModel.Entity.AttendanceViolationRuleEnabled }">
									<div class="rule-label">
										<span class="rule-text">早退阈值</span>
									</div>
									<div class="rule-input-group">
										<el-input-number
											v-model="stateData.vmModel.Entity.EarlyLeaveMinutesThreshold"
											:disabled="!stateData.vmModel.Entity.AttendanceViolationRuleEnabled"
											class="rule-input"
											:min="0"
										></el-input-number>
										<span class="rule-unit">分钟</span>
										<span class="rule-desc">早于标准下班时间多少分钟算作早退</span>
									</div>
								</div>
								<div class="rule-item" :class="{ 'rule-disabled': !stateData.vmModel.Entity.AttendanceViolationRuleEnabled }">
									<div class="rule-label">
										<span class="rule-text">迟到记旷工阈值</span>
									</div>
									<div class="rule-input-group">
										<el-input-number
											v-model="stateData.vmModel.Entity.AbsenceByLateMinutesThreshold"
											:disabled="!stateData.vmModel.Entity.AttendanceViolationRuleEnabled"
											class="rule-input"
											:min="0"
										></el-input-number>
										<span class="rule-unit">分钟</span>
										<span class="rule-desc">迟到超过多少分钟记为旷工</span>
									</div>
								</div>
								<div class="rule-item" :class="{ 'rule-disabled': !stateData.vmModel.Entity.AttendanceViolationRuleEnabled }">
									<div class="rule-label">
										<span class="rule-text">早退记旷工阈值</span>
									</div>
									<div class="rule-input-group">
										<el-input-number
											v-model="stateData.vmModel.Entity.AbsenceByEarlyLeaveMinutesThreshold"
											:disabled="!stateData.vmModel.Entity.AttendanceViolationRuleEnabled"
											class="rule-input"
											:min="0"
										></el-input-number>
										<span class="rule-unit">分钟</span>
										<span class="rule-desc">早退超过多少分钟记为旷工</span>
									</div>
								</div>
								<div class="rule-item" :class="{ 'rule-disabled': !stateData.vmModel.Entity.AttendanceViolationRuleEnabled }">
									<div class="rule-label">
										<span class="rule-text">合计偏差记旷工阈值</span>
									</div>
									<div class="rule-input-group">
										<el-input-number
											v-model="stateData.vmModel.Entity.AbsenceByTotalDeviationMinutesThreshold"
											:disabled="!stateData.vmModel.Entity.AttendanceViolationRuleEnabled"
											class="rule-input"
											:min="0"
										></el-input-number>
										<span class="rule-unit">分钟</span>
										<span class="rule-desc">迟到和早退时间合计超过多少分钟记为旷工</span>
									</div>
								</div>
							</div>
						</div>

						<div class="form-section">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-time"></i>
								<span>工时折算</span>
							</div>

							<div class="worktime-settings-row">
								<div class="worktime-item">
									<div class="worktime-label">
										<span>标准工作时长</span>
									</div>
									<el-form-item
										prop="Entity.StandardWorkMinutes"
										:rules="[{ required: true, message: '标准工作时长为必填项', trigger: 'blur' }]"
										class="inline-form-item"
									>
										<el-input-number v-model="stateData.vmModel.Entity.StandardWorkMinutes" class="worktime-input" :min="0"></el-input-number>
									</el-form-item>
									<span class="rule-unit">分钟</span>
								</div>
								<div class="worktime-item">
									<div class="worktime-label">
										<span>折算出勤天数</span>
									</div>
									<el-form-item
										prop="Entity.AttendanceDays"
										:rules="[{ required: true, message: '折算出勤天数为必填项', trigger: 'blur' }]"
										class="inline-form-item"
									>
										<el-input-number
											v-model="stateData.vmModel.Entity.AttendanceDays"
											class="worktime-input"
											:min="0"
											:precision="2"
										></el-input-number>
									</el-form-item>
									<span class="rule-unit">天</span>
								</div>
							</div>
						</div>
					</el-form>
				</el-card>
			</el-tab-pane>

			<el-tab-pane label="补贴规则列表" name="subsidyrules" v-if="stateData.vmModel.Entity.ID">
				<SysAttendanceSubsidyRule :search-bar="false" :toolbar="true" :is-disabled="false" :entity-id="stateData.vmModel.Entity.ID" />
			</el-tab-pane>
		</el-tabs>
	</div>
</template>

<!--suppress JSAnnotator -->
<script setup lang="ts" name="message._system.common.vm.add;false">
import ElMessage from 'element-plus/es/components/message/index';
import { reactive, ref, getCurrentInstance, onMounted, computed, nextTick, ComponentInternalInstance } from 'vue';
import { SysAttendanceShiftApi as api } from '/@/views/hr/sysattendanceshift/api';
import other from '/@/utils/other';
import { ISysAttendanceShiftVm } from '/@/views/hr/sysattendanceshift/api/interface';
import { IViewModel } from '/@/types/common';
import ScheduleSettings from '/@/components/scheduleSettings/index.vue';
import SysAttendanceSubsidyRule from '/@/views/hr/sysattendancesubsidyrule/index.vue';

const BUTTON_TEXTS = {
	SAVE: '保存',
	SUBMIT: '提交',
	CLOSE: '关闭',
} as const;
const ci = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);
const formRef = ref();
const hasSavedOnce = ref(false);
const activeTab = ref('main');
// 预定义颜色选项
const predefineColors = ref([
	'#FF6B6B', // 红色系
	'#4ECDC4', // 青色系
	'#45B7D1', // 蓝色系
	'#96CEB4', // 绿色系
	'#FFEAA7', // 黄色系
	'#DDA0DD', // 紫色系
	'#98D8C8', // 薄荷绿
	'#F7DC6F', // 淡黄色
	'#BB8FCE', // 淡紫色
	'#85C1E9', // 淡蓝色
]);

const stateData = reactive<IViewModel<ISysAttendanceShiftVm>>({
	vmModel: {
		Entity: {
			Name: null,
			DisplayColor: '#409EFF',
			Tag: null,
			IsEnabled: true,
			Remark: null,
			WorkStartDayOffset: '当日',
			WorkStartTime: null,
			WorkStartPunchStartDayOffset: '当日',
			WorkStartPunchStartTime: null,
			WorkStartPunchEndDayOffset: '当日',
			WorkStartPunchEndTime: null,
			WorkEndDayOffset: '当日',
			WorkEndTime: null,
			WorkEndPunchStartDayOffset: '当日',
			WorkEndPunchStartTime: null,
			WorkEndPunchEndDayOffset: '当日',
			WorkEndPunchEndTime: null,
			AttendanceViolationRuleEnabled: true,
			LateMinutesThreshold: 15,
			EarlyLeaveMinutesThreshold: 15,
			AbsenceByLateMinutesThreshold: 120,
			AbsenceByEarlyLeaveMinutesThreshold: 120,
			AbsenceByTotalDeviationMinutesThreshold: 240,
			StandardWorkMinutes: 480,
			AttendanceDays: null,
			SubsidyRuleEnabled: false,
			IsHolidayScheduled: false,
			WorkDays: null,
			IsDefault: false,
			Order: 0,
		},
		ActionName: null,
		IsMyApprove: null,
		WorkDays: ['星期一', '星期二', '星期三', '星期四', '星期五'],
	},
});

const handleApiResponse = (response: any, isSubmit = false) => {
	if (isSubmit) {
		ElMessage.success(ci.proxy?.$t('message._system.common.vm.submittip') || '提交成功');
	} else {
		ElMessage.success(ci.proxy?.$t('message._system.common.vm.savetip') || '保存成功');
	}
	emit('refresh');

	// 统一处理ID设置
	if (response?.Entity?.ID) {
		stateData.vmModel.Entity = response.Entity;
	} else if (response?.ID) {
		stateData.vmModel.Entity.ID = response.ID;
	}
	if (isSubmit) {
		closeDialog();
	} else {
		hasSavedOnce.value = true;
	}
	loading.value = false;

	nextTick(() => {
		setupHeaderButtons();
	});
};

const handleError = (error: any) => {
	other.setFormError(ci, error);
	loading.value = false;
};

const handleApiRequest = (apiCall: () => Promise<any>, beforeSubmit: () => void, isSubmit = false) => {
	other.validateFormWithMessage(formRef.value, () => {
		loading.value = true;
		beforeSubmit();
		apiCall()
			.then((response: any) => handleApiResponse(response))
			.catch(handleError);
	});
};
// 取消
const onClose = () => {
	closeDialog();
};

// 保存
const onSave = () => {
	handleApiRequest(
		() => {
			// 创建一个深拷贝，确保新增时不发送无效的 ID 字段
			const submitData = JSON.parse(JSON.stringify(stateData.vmModel));
			if (!submitData.Entity.ID) {
				// 如果没有有效的 ID，删除该字段
				delete submitData.Entity.ID;
			}
			return api().add(submitData);
		},
		() => {},
		true
	);
};
// 提交
const onSubmit = () => {
	closeDialog();
};

const workStartTime = computed<Date | null>({
	get: () => timeSpanToDate(stateData.vmModel.Entity.WorkStartTime),
	set: (value: Date | null) => {
		stateData.vmModel.Entity.WorkStartTime = dateToTimeSpan(value);
	},
});

const timeSpanToDate = (timeSpan: string | null): Date | null => {
	if (!timeSpan) return null;
	const parts = timeSpan.split(':');
	if (parts.length !== 3) return null;
	const [hours, minutes, seconds] = parts;
	const date = new Date();
	date.setHours(+hours, +minutes, +seconds, 0);
	return date;
};

const dateToTimeSpan = (date: Date | null): string | null => {
	if (!date) return null;
	const hours = date.getHours().toString().padStart(2, '0');
	const minutes = date.getMinutes().toString().padStart(2, '0');
	const seconds = date.getSeconds().toString().padStart(2, '0');
	return `${hours}:${minutes}:${seconds}`;
};

const workStartPunchStartTime = computed<Date | null>({
	get: () => timeSpanToDate(stateData.vmModel.Entity.WorkStartPunchStartTime),
	set: (value: Date | null) => {
		stateData.vmModel.Entity.WorkStartPunchStartTime = dateToTimeSpan(value);
	},
});

const workStartPunchEndTime = computed<Date | null>({
	get: () => timeSpanToDate(stateData.vmModel.Entity.WorkStartPunchEndTime),
	set: (value: Date | null) => {
		stateData.vmModel.Entity.WorkStartPunchEndTime = dateToTimeSpan(value);
	},
});

const workEndTime = computed<Date | null>({
	get: () => timeSpanToDate(stateData.vmModel.Entity.WorkEndTime),
	set: (value: Date | null) => {
		stateData.vmModel.Entity.WorkEndTime = dateToTimeSpan(value);
	},
});

const workEndPunchStartTime = computed<Date | null>({
	get: () => timeSpanToDate(stateData.vmModel.Entity.WorkEndPunchStartTime),
	set: (value: Date | null) => {
		stateData.vmModel.Entity.WorkEndPunchStartTime = dateToTimeSpan(value);
	},
});

const workEndPunchEndTime = computed<Date | null>({
	get: () => timeSpanToDate(stateData.vmModel.Entity.WorkEndPunchEndTime),
	set: (value: Date | null) => {
		stateData.vmModel.Entity.WorkEndPunchEndTime = dateToTimeSpan(value);
	},
});

// 加载选择列表数据
const loadData = async () => {
	await Promise.allSettled([]);
};

const initializePageData = () => {
	const wtmdata = ci.attrs['wtmdata'] as any;
	if (wtmdata?.ID) {
		stateData.vmModel.Entity.ID = wtmdata.ID;
		hasSavedOnce.value = true;
	}
};
// 页面加载时
onMounted(async () => {
	loading.value = true;
	initializePageData();

	try {
		// 并行加载选择列表数据
		await loadData();
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
		nextTick(() => {
			setupHeaderButtons();
		});
	}
});

// 定义子组件向父组件传值事件
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);

// 关闭弹窗
const closeDialog = () => {
	emit('closeDialog');
};

const setupHeaderButtons = () => {
	const headerButtons = [
		{
			text: BUTTON_TEXTS.SAVE,
			type: 'info',
			onClick: onSave,
			visible: !hasSavedOnce.value,
		},
		{
			text: BUTTON_TEXTS.SUBMIT,
			type: 'primary',
			onClick: onSubmit,
			visible: hasSavedOnce.value,
		},
		{
			text: BUTTON_TEXTS.CLOSE,
			type: 'default',
			onClick: onClose,
			visible: true,
		},
	];
	emit('updateHeaderButtons', headerButtons);
};
</script>
